package com.shelpe.services.auth.provider.request;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;

public class OAuth2ReqeustFactory extends DefaultOAuth2RequestFactory {
	
	private final static String[] DEFAULT_KEYS = {OAuth2Utils.CLIENT_ID, OAuth2Utils.GRANT_TYPE, OAuth2Utils.SCOPE, OAuth2Utils.RESPONSE_TYPE};

	public OAuth2ReqeustFactory(ClientDetailsService clientDetailsService) {
		super(clientDetailsService);
	}

	@Override
	public OAuth2Request createOAuth2Request(AuthorizationRequest request) {
		OAuth2Request req = super.createOAuth2Request(request);
		this.fillupAdditionalParameters(req, request.getRequestParameters());
		return req;
	}

	@Override
	public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest) {
		OAuth2Request req = super.createOAuth2Request(client, tokenRequest);
		this.fillupAdditionalParameters(req, tokenRequest.getRequestParameters());
		return req;
	}
	
	private void fillupAdditionalParameters(OAuth2Request req, Map<String, String> parameters){
		if(parameters != null){
			for(Entry<String, String> en: parameters.entrySet()){
				if(!ArrayUtils.contains(DEFAULT_KEYS, en.getKey())){
					req.getExtensions().put(en.getKey(), en.getValue());
				}
			}
		}
	}

}
